package com.example.administrator.baikangxing.activity;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.SurfaceView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.administrator.baikangxing.R;
import com.example.administrator.baikangxing.ronglian.SDKCoreHelper;
import com.example.administrator.baikangxing.ronglian.VoIPCallHelper;
import com.example.administrator.baikangxing.utils.CallFailReason;
import com.example.administrator.baikangxing.utils.LogUtil;
import com.example.administrator.baikangxing.utils.ScreenUtils;
import com.example.administrator.baikangxing.utils.Utils;
import com.yuntongxun.ecsdk.ECDevice;
import com.yuntongxun.ecsdk.ECError;
import com.yuntongxun.ecsdk.ECVoIPCallManager;
import com.yuntongxun.ecsdk.ECVoIPSetupManager;
import com.yuntongxun.ecsdk.VideoRatio;
import com.yuntongxun.ecsdk.voip.video.ECCaptureView;

public class VideoActivity extends BaseActivity implements VoIPCallHelper.OnCallEventNotifyListener {
    private SurfaceView mVideoView;
    private ECCaptureView mLocalView;
    private TextView tv_camera;
    private ImageView mCameraSwitch;
    private ImageView id_ivMute;
    private View id_flView;
    private View mViewLayout;
    private ImageView video_botton_begin;
    private ImageView video_botton_end;
    private RelativeLayout id_rlBottom;
    private TextView id_tvCallName;
    private ImageView id_ivLound;
    private LinearLayout id_llPhoneCall;

    private ECVoIPCallManager.CallType mCallType = ECVoIPCallManager.CallType.VIDEO;
    /**呼叫唯一标识号*/
    protected String mCallId;
    private Integer sreenWidth;
    /**是否来电*/
    protected boolean mIncomingCall = false;
    /**通话昵称*/
    protected String mCallName;
    /**通话号码*/
    protected String mCallNumber;
    protected String mPhoneNumber;
    /**透传号码参数*/
    private static final String KEY_TEL = "tel";
    /**透传名称参数*/
    private static final String KEY_NAME = "nickname";
    private static final String KEY_CONFIG = "confid";
    private static final String KEY_CONFIG_TYPE = "conftype";
    private static final String KEY_CONFIG_SUD = "sud";

    private boolean isSwitch = true;
    private boolean isMute = false;
    private boolean isHand = true;

    @Override
    public int getContentViewLayoutId() {
        return R.layout.activity_video;
    }

    @Override
    public void initView() {
        mVideoView = findView(R.id.video_mVideoView);
        mLocalView = findView(R.id.video_mLocalView);
        tv_camera = (TextView) findViewById(R.id.tv_camera);
        mCameraSwitch = (ImageView) findViewById(R.id.id_ivCameraSwitch);
        video_botton_begin = (ImageView) findViewById(R.id.video_botton_begin);
        video_botton_end = (ImageView) findViewById(R.id.video_botton_end);
        id_rlBottom = (RelativeLayout) findViewById(R.id.id_rlBottom);
        id_flView = findViewById(R.id.id_flView);
        mViewLayout = findViewById(R.id.mViewLayout);
        id_tvCallName = (TextView) findViewById(R.id.id_tvCallName);
        id_ivMute = (ImageView) findViewById(R.id.id_ivMute);
        id_ivLound = (ImageView) findViewById(R.id.id_ivLound);
        id_llPhoneCall = (LinearLayout) findViewById(R.id.id_llPhoneCall);
        sreenWidth = new Integer(ScreenUtils.getScreenWidth(this));
        if (sreenWidth == null)
            return;
        try {
            SDKCoreHelper.getVoIPSetManager().setVideoView(mVideoView,mLocalView);
            SDKCoreHelper.getVoIPSetManager().setAudioConfigEnabled(ECVoIPSetupManager.AudioType.AUDIO_EC ,
                    true , ECVoIPSetupManager.AudioMode.EC_Conference);
        } catch (Exception e) {
            e.printStackTrace();
            finish();
            return;
        }
        mIncomingCall = getIntent().getBooleanExtra("mIncomingCall",false);
        String serial = getIntent().getStringExtra("serial");
        if (mIncomingCall){
            video_botton_begin.setVisibility(View.GONE);
            tv_camera.setText(R.string.ec_voip_call_connecting_server);
            //说明：mCurrentCallId如果返回空则代表呼叫失败，可能是参数错误引起。否则返回是一串数字，是当前通话的标识。
            mCallId = VoIPCallHelper.makeCall(mCallType, serial);
            LogUtil.e("呼叫结果为"+mCallId);
        }else {
            // 透传信息
            String[] infos = getIntent().getExtras().getStringArray(ECDevice.REMOTE);
            if (infos != null && infos.length > 0) {
                for (String str : infos) {
                    if (str.startsWith(KEY_TEL)) {
                        mPhoneNumber = Utils.getLastwords(str, "=");
                    }else if (str.startsWith(KEY_NAME)) {
                        mCallName = Utils.getLastwords(str, "=");
                        id_tvCallName.setText(mCallName);
                    }
                }
            }
            tv_camera.setText((mCallName == null ? mCallNumber : mCallName) + getString(R.string.ec_voip_invited_video_tip));
        }
        mCameraSwitch.setOnClickListener(listener);
        video_botton_begin.setOnClickListener(listener);
        video_botton_end.setOnClickListener(listener);
        id_ivLound.setOnClickListener(listener);
        id_ivMute.setOnClickListener(listener);
    }


    @Override
    public void initListener() {

    }

    @Override
    public void initData() {

    }

    @Override
    public void onCallProceeding(String callId) {
        if (callId != null && callId.equals(mCallId)) {
            tv_camera.setText(getString(R.string.ec_voip_call_connect));
        }
    }

    @Override
    public void onMakeCallback(ECError arg0, String arg1, String arg2) {

    }

    @Override
    public void onCallAlerting(String callId) {
        if (callId != null && callId.equals(mCallId)) {// 等待对方接受邀请...
            tv_camera.setText(getString(R.string.str_tips_wait_invited));
        }
    }

    private void switchCamera(){
        if(mLocalView != null) {
            mLocalView.switchCamera();
        }
    }

    @Override
    public void onCallAnswered(String callId) {
        if (callId != null && callId.equals(mCallId)) {
            if(SDKCoreHelper.getVoIPSetManager() != null) {
                SDKCoreHelper.getVoIPSetManager().enableLoudSpeaker(true);
                SDKCoreHelper.getVoIPSetManager().setMute(true);
                isMute = VoIPCallHelper.getMute();
                isHand = VoIPCallHelper.getHandFree();
                id_flView.setVisibility(View.VISIBLE);
                mViewLayout.setVisibility(View.VISIBLE);
                id_rlBottom.setVisibility(View.GONE);
                id_ivMute.setClickable(true);
                mCameraSwitch.setClickable(true);
                id_ivLound.setClickable(true);
                Log.w("onCallAnswered", "扬声器状态:"+ ECDevice.getECVoIPSetupManager().getLoudSpeakerStatus());
            }
        }
    }

    @Override
    public void onMakeCallFailed(String callId, int reason) {
        if (callId != null && callId.equals(mCallId)) {
            VoIPCallHelper.releaseCall(mCallId);
            id_llPhoneCall.setVisibility(View.INVISIBLE);
            id_flView.setVisibility(View.GONE);
            mViewLayout.setVisibility(View.GONE);
            id_rlBottom.setVisibility(View.VISIBLE);
            id_ivMute.setClickable(true);
            mCameraSwitch.setClickable(true);
            id_ivLound.setClickable(true);
            tv_camera.setText(CallFailReason.getCallFailReason(reason));
            Log.e("onMakeCallFailed", "call failed!!!="+reason);
            new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {

                @Override
                public void run() {
                    finish();
                }
            }, 800);
        }
    }

    @Override
    public void onCallReleased(String callId) {
        if (callId != null && callId.equals(mCallId)) {
            VoIPCallHelper.releaseMuteAndHandFree();
        }
        id_llPhoneCall.setVisibility(View.INVISIBLE);
        id_flView.setVisibility(View.GONE);
        mViewLayout.setVisibility(View.GONE);
        id_rlBottom.setVisibility(View.VISIBLE);
        tv_camera.setText(R.string.ec_voip_calling_finish);
        new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {

            @Override
            public void run() {
                finish();
            }
        }, 800);
    }

    @Override
    public void onVideoRatioChanged(VideoRatio videoRatio) {
        if(mVideoView != null && videoRatio != null) {
            LogUtil.e("onVideoRatioChanged:width="+videoRatio.getWidth()+",height="+videoRatio.getHeight());
//            FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) mVideoView.getLayoutParams();
//            if(lp.height*videoRatio.getWidth()!=sreenWidth * videoRatio.getHeight()){
//                lp.height = sreenWidth * videoRatio.getHeight()/videoRatio.getWidth();
//                lp.width = sreenWidth;
//                mVideoView.setLayoutParams(lp);
//            }
            mVideoView.getHolder().setFixedSize(videoRatio.getWidth(),videoRatio.getHeight());
        }
    }

    private View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()){
                case R.id.video_botton_begin:
                    video_botton_begin.setVisibility(View.GONE);
                    id_rlBottom.setVisibility(View.GONE);
                    id_flView.setVisibility(View.VISIBLE);
                    mViewLayout.setVisibility(View.VISIBLE);
                    mCallId = getIntent().getStringExtra(ECDevice.CALLID);
                    VoIPCallHelper.acceptCall(mCallId);
                    break;
                case R.id.video_botton_end:
                    mCallId = getIntent().getStringExtra(ECDevice.CALLID);
                    try {
                        if (mCallId != null) {
                            if (mIncomingCall) {
                                VoIPCallHelper.rejectCall(mCallId);
                                finish();
                            } else {
                                VoIPCallHelper.releaseCall(mCallId);
                            }
                        }else finish();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case R.id.id_ivCameraSwitch:
                    if (isSwitch){
                        isSwitch = false;
                        mCameraSwitch.setImageResource(R.drawable.carmer_white);
                    }else {
                        isSwitch = true;
                        mCameraSwitch.setImageResource(R.drawable.carmer_grey);
                    }
                    switchCamera();
                    break;
                case R.id.id_ivMute:
                    if (!isMute){
                        isMute = false;
                        id_ivMute.setImageResource(R.drawable.silence_grey);
                    }else {
                        isMute = true;
                        id_ivMute.setImageResource(R.drawable.silence_white);
                    }
                    VoIPCallHelper.setMute();
                    break;
                case R.id.id_ivLound:
                    if (isHand){
                        isHand = false;
                        id_ivLound.setImageResource(R.drawable.lound_grey);
                    }else {
                        isHand = true;
                        id_ivLound.setImageResource(R.drawable.lound_white);
                    }
                    VoIPCallHelper.setHandFree();
                    break;
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            if(mCallId!=null){
                VoIPCallHelper.releaseCall(mCallId);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        VoIPCallHelper.mHandlerVideoCall = false;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mCallType == ECVoIPCallManager.CallType.VIDEO) {
            if(mLocalView != null) {
                mLocalView.onResume();
            }
        }
        VoIPCallHelper.setOnCallEventNotifyListener(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
    }
}
